package com.snailhd.pipeline;

import com.snailhd.common.entity.IResult;
import lombok.NoArgsConstructor;

import java.util.concurrent.*;

/**
 * @author hd
 * @description
 * @date 2019-11-23 14:25
 */

@NoArgsConstructor
public class PipelineFuture<T> implements Future<T> {

    private CountDownLatch latch = new CountDownLatch(1);

    private T response;

    public PipelineFuture(T response) {
        this.response = response;
    }

    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        return false;
    }


    @Override
    public boolean isCancelled() {
        return false;
    }


    @Override
    public boolean isDone() {
        if (response != null) {
            return true;
        }
        return false;
    }


    @Override
    public T get() throws InterruptedException, ExecutionException {
        latch.await();
        return this.response;
    }

    public T get(long timeout) throws InterruptedException, ExecutionException, TimeoutException {
        return get(timeout, TimeUnit.SECONDS);
    }

    @Override
    public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        if (latch.await(timeout, unit)) {
            return this.response;
        }
        return null;
    }


}
